package com.x.gzcrm.web.security;

import com.x.gzcrm.model.Permission;
import com.x.gzcrm.service.IPermissionService;
import com.x.gzcrm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.thymeleaf.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Configuration
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IPermissionService pmsService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //这里要做用户认证
        System.out.println("用户名:"+username);

        //1根据用户名从数据库查找有没有用户信息
        com.x.gzcrm.model.User dbUser = iUserService.findByUsername(username);
        System.out.println("dbUser="+dbUser);
            if(dbUser==null)
            {
                throw new UsernameNotFoundException("用户名"+username+"的用户不存在");
            }
        //2 如果有用户信息，返回有一个USer对象
        String pwd= passwordEncoder.encode(dbUser.getPassword());
        System.out.println("密码加密后"+pwd);

        return  new User(username, //用户名
        pwd,//密码从数据库获取，密码需要加密器进行加密
                getCurrentUserAuthorities(dbUser.getId()) );//给当前用户授权
        // AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")
    }
    //获取当前用户拥有的权限
    public Collection<? extends GrantedAuthority> getCurrentUserAuthorities(Integer userId)
    {
        List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
        //查当前用户拥有的权限
        List<Permission> pmsList = pmsService.findPermissionListByUserId(userId);
        for(Permission p : pmsList){
            if(!StringUtils.isEmpty(p.getAuthorization_flag())&&p.getAuthorization_flag()!=null){
                list.add(new SimpleGrantedAuthority(p.getAuthorization_flag()));
            }
        }

//        list.add(new SimpleGrantedAuthority("COURSEORDER_READ"));
//        list.add(new SimpleGrantedAuthority("COURSEORDER_DELETE"));
//        list.add(new SimpleGrantedAuthority("COURSEORDER_EDIT"));
//        list.add(new SimpleGrantedAuthority("COURSEORDER_ADD"));
        return list;
    }
}

